/**
 * @author 何杰
 * @version 1.0
 */
public class Trap {
    public static void main(String[] args) {
        int[] test = {0,1,0,2,1,0,1,3,2,1,2,1};
        int res = trap(test);
        System.out.println(res);

    }

    public static int trap(int[] height) {
        int left = 0,right = height.length - 1;
        int res = 0;
        int leftMax = 0, rightMax = 0;
        while(left < right) {
            leftMax = Math.max(leftMax, height[left]);
            rightMax = Math.max(rightMax, height[right]);
            if(height[left] < height[right]) {
                res += leftMax - height[left];
                ++left;
            } else {
                res += rightMax - height[right];
                --right;
            }
        }
        return res;
    }
}
